package cdc.retrofit.official.dynamicbaseurl;

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Response;
import retrofit2.Retrofit;
/**
 * 本示例使用OkHttp拦截器在运行时动态更改目标主机名。
通常，这将用于实现客户端负载平衡或使用最接近地理位置的网络服务器。
 * @author cdc
 *
 */
public class DynamicBaseUrl {
	public static void main(String... args) throws IOException {
		HostSelectionInterceptor hostSelectionInterceptor = new HostSelectionInterceptor();

		OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(hostSelectionInterceptor).build();

		Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.github.com/").callFactory(okHttpClient).build();

		Pop pop = retrofit.create(Pop.class);

		Response<ResponseBody> response1 = pop.robots().execute();
		System.out.println("Response from: " + response1.raw().request().url());
		System.out.println(response1.body().string());

		hostSelectionInterceptor.setHost("www.pepsi.com");

		Response<ResponseBody> response2 = pop.robots().execute();
		System.out.println("Response from: " + response2.raw().request().url());
		System.out.println(response2.body().string());
	}

}
